﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WCF.Hosting;
using System.ServiceModel;
using System.Drawing;


namespace FrameDetectionTest
{
    public class CIM
    {
        #region cim
        //提供创建和管理不同类型的双通道的方式，客户端使用这些通道在服务终结点发送和接收消息。
        //并在这里回调方法TodoServiceCallback
        public static DuplexChannelFactory<ITodoService> channel = new DuplexChannelFactory<ITodoService>(new InstanceContext(new TodoServiceCallback()), "push");
        ITodoService Proxy = channel.CreateChannel();

        public static DuplexChannelFactory<ITodoService> channel2 = new DuplexChannelFactory<ITodoService>(new InstanceContext(new TodoServiceCallback()), "push");
        ITodoService Proxy2 = channel2.CreateChannel();

        public event PrintMsgEventHandle printmessage;

        public enum eStatus { OnLine, OffLine }
        public eStatus Status { private set; get; } = eStatus.OffLine;
        public bool IsConnect { set; get; } = false;
        public string EQPID { set; get; }

        //eqpcall cim data
        public class EQPCALLCIMDATA
        {
            public string TagName { set; get; }
            public string RequestNo { set; get; }
            public string EqpSeq { set; get; }
            public string Sn { set; get; }
            public string ResultFlag { set; get; }
            public string NameFlag { set; get; }
            public string Eqpid { set; get; }//站位ID
            public string ErrorCode { set; get; }

            public string TestSlot { set; get; }
            public string TestTime { set; get; }
            public string ProductSN { set; get; }
        }
        public class RT_EQPCALLCIMDATA
        {
            public string RTMsg { set; get; }
            public string RTFlag { set; get; }
        }
        public class CIM_TO_STATION
        {
            public string TagName { set; get; }
            public string RequestNo { set; get; }
            public string EqpSeq { set; get; }

            //流水板ID
            public string Sn { set; get; }
            public string MesFlag { set; get; }
            public string NameFlag { set; get; }

            //当前站ID
            public string Eqpid { set; get; }
            public DateTime UpdateTime { set; get; }
        }
        //Connect Cim
        public void ConnectCIMServer()
        {
            try
            {
                Proxy.OffLine();
                printmessage.Invoke("已连接CIM服务", Color.Green);

                channel.Faulted += Channel_Faulted;
                channel2.Faulted += Channel2_Faulted;

                IsConnect = true;
            }
            catch (Exception ex)
            {
                printmessage(string.Format("连接CIM服务失败：{0}", ex.Message), Color.Red);
                Log.Print(ex.Message, Log.LogType.error);
            }
        }// Connect CIM Server
        private void Channel2_Faulted(object sender, EventArgs e)
        {
            IsConnect = false;
            printmessage.Invoke("Channel2 通道已断开请重新创建", Color.Red);
            Log.Print("Channel2 通道已断开请重新创建");
        }
        private void Channel_Faulted(object sender, EventArgs e)
        {
            IsConnect = false;
            printmessage.Invoke("Channel 通道已断开请重新创建", Color.Red);
            Log.Print("Channel2 通道已断开请重新创建");
        }
        public void OnLine()
        {
            //通道不未空
            if (Proxy != null)
            {
                if (!IsConnect)
                {
                    throw new Exception("CIM系统未连接");
                }
                Proxy.OnLine();
            }
            //通道为空
            else
            {
                throw new Exception("Channel 通道未创建创建");
            }
        }

        public void OffLine()
        {
            if (Proxy != null)
            {
                if (!IsConnect)
                {
                    //printmessage.Invoke("CIM系统未连接", Color.Red);
                    return;
                }
                Proxy.OffLine();
            }
            else
            {
                printmessage.Invoke("Channel 通道未创建创建", Color.Red);
            }
        }// Close

        public void RequestRFID()
        {
            try
            {
                if (TodoServiceCallback.IsWork) return;
                string TagName = string.Empty;
                string RequestNo = string.Empty;

                if (TodoServiceCallback.current_cim_to_station != null)
                {
                    TagName = TodoServiceCallback.current_cim_to_station.TagName;
                    RequestNo = TodoServiceCallback.current_cim_to_station.RequestNo;
                }
                else
                {
                    TagName = "";
                    RequestNo = "500";
                }
                EQPCALLCIMDATA eqp_call_cim_data = new EQPCALLCIMDATA
                {
                    TagName = TagName,
                    RequestNo = RequestNo,
                    EqpSeq = "0",
                    Sn = "0",
                    ResultFlag = "3",    // 1:Ok   2:Fail
                    NameFlag = "0",
                    Eqpid = EQPID,
                    ErrorCode = "0",
                };
                string sJson = JsonConvert.SerializeObject(eqp_call_cim_data);
                Log.Print(string.Format("PC -> CIM: SendJson2({0})", sJson), Log.LogType.cim);
                Proxy2.SendJson2(sJson);
                Log.Print("Request RFID Send Ok");
            }
            catch (Exception ex)
            {
                printmessage(string.Format("Repuest RFID failed: ", ex.Message), Color.Red);
                Log.Print(string.Format("Repuest RFID failed: ", ex.Message));
            }
        }

        public void CheckChannel()
        {
            try
            {
                if (TodoServiceCallback.IsWork) return;

                EQPCALLCIMDATA eqp_call_cim_data = new EQPCALLCIMDATA
                {
                    TagName = "ChannelHeartbeat",
                    RequestNo = "999",
                    EqpSeq = "9",
                    Sn = "9999999999",
                    ResultFlag = "9",    // 1:Ok   2:Fail
                    NameFlag = "9999",
                    Eqpid = EQPID,
                    ErrorCode = "9999",
                };
                string sJson = JsonConvert.SerializeObject(eqp_call_cim_data);
                Proxy.SendJson2(sJson);
                Proxy2.SendJson2(sJson);
                Log.Print("Check CIM Channel", Log.LogType.workmessage);
            }
            catch (Exception ex)
            {
                Log.Print(string.Format("Check cim channel failed： {0}", ex.Message), Log.LogType.workmessage);
            }
        }

        public void ReportToCIM(EQPCALLCIMDATA eqp_call_cim_data)
        {
            string sJson = JsonConvert.SerializeObject(eqp_call_cim_data);
            Log.Print(string.Format("PC -> CIM: SendJson2({0})", sJson), Log.LogType.cim);
            try
            {
                Proxy2.SendJson2(sJson);
                Log.Print("Report To CIM Data Ok", Log.LogType.cim);
                printmessage("已上报CIM系统", Color.Green);
            }
            catch (Exception ex)
            {
                Log.Print(string.Format("Report to cim failed: {0}  {1}", ex.Message, sJson), Log.LogType.error);
                printmessage(string.Format("Report to cim failed: {0}  {1}", ex.Message, sJson), Color.Red);
            }
        }

        #endregion

    }
}
